package vip.xiaonuo.biz.modular.lancerTask;

import cn.hutool.core.collection.ListUtil;
import com.alibaba.fastjson.JSON;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.ExistsQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import vip.xiaonuo.biz.modular.esmapping.BizGoodsBoxESMapper;
import vip.xiaonuo.biz.modular.pojo.domain.BizGoodsBox;
import vip.xiaonuo.common.pojo.DbEnum;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
@Slf4j
public class SyncTask {
    @Autowired
    BizGoodsBoxESMapper boxESMapper;
    @XxlJob("syncSuggestionAndAllOnES")
    // TODO: 使用定时任务同步词条
    public void syncSuggestionAndAllOnES() {
        SearchRequest searchRequest = new SearchRequest(DbEnum.ESIndex);
        SearchSourceBuilder builder = new SearchSourceBuilder();
        // 构建查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        ExistsQueryBuilder existsQueryBuilder = QueryBuilders.existsQuery("all");
        boolQueryBuilder.mustNot(existsQueryBuilder);
        builder.query(boolQueryBuilder);

        searchRequest.source(builder);
        try {
            SearchResponse response = boxESMapper.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits responseHits = response.getHits();
            // 新的更新序列
            List<BizGoodsBox> newBoxList=new ArrayList<>(responseHits.getHits().length);
            for (SearchHit hit : responseHits.getHits()) {
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                BizGoodsBox user = JSON.parseObject(JSON.toJSONString(sourceAsMap), BizGoodsBox.class);
                BizGoodsBox bizGoodsBox = new BizGoodsBox();
                BeanUtils.copyProperties(user,bizGoodsBox);
                // 设置id
                bizGoodsBox.setId(hit.getId());
                // 设置自动补全的字段
                bizGoodsBox.setSuggestions(ListUtil.of(user.getGoodsBoxName(),user.getBrandName()));
                bizGoodsBox.setAll(user.getGoodsBoxName());
                newBoxList.add(bizGoodsBox);
            }
            // 更新文档
            boxESMapper.updateBatchByIds(newBoxList);
            log.info("词条更新完成{}",newBoxList.size());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
